import 'package:bilibili/core/sun_state.dart';
import 'package:bilibili/http/core/sun_error.dart';
import 'package:bilibili/http/dao/home_dao.dart';
import 'package:bilibili/model/home_model.dart';
import 'package:bilibili/navigator/sun_navigator.dart';
import 'package:bilibili/page/home_tab_page.dart';
import 'package:bilibili/util/color.dart';
import 'package:bilibili/util/toast_util.dart';
import 'package:bilibili/widget/navigation_bar.dart';
import 'package:flutter/material.dart';
import 'package:underline_indicator/underline_indicator.dart';

class HomePage extends StatefulWidget {
  final ValueChanged<int>? onJumpTo;

  const HomePage({Key? key, this.onJumpTo}) : super(key: key);
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends SunState<HomePage>
    with AutomaticKeepAliveClientMixin, TickerProviderStateMixin {
  var listener;
  late TabController _tabController;
  List<CategoryModel> categoryList = [];
  List<BannerModel> bannerList = [];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: categoryList.length, vsync: this);
    SunNavigator.getInstance().addListener(this.listener = (current, pre) {
      print('home:current:${current.page}');
      print('home:pre:${pre.page}');
      if (widget == current.page || current.page is HomePage) {
        print('首页:onResume');
      } else if (widget == pre?.page || pre?.page is HomePage) {
        print('首页:onPause');
      }
    });
    loadData();
  }

  @override
  void dispose() {
    SunNavigator.getInstance().removeListener(this.listener);
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      body: Column(
        children: [
          NavigationBar(
            height: 50,
            child: _appBar(),
          ),
          Container(
            color: Colors.white,
            padding: EdgeInsets.only(top: 30),
            child: _tabBar(),
          ),
          Flexible(
              child: TabBarView(
                  controller: _tabController,
                  children: categoryList
                      .map((c) => HomeTabPage(
                            name: c.name ?? "",
                            bannerList: c.name == '推荐' ? bannerList : null,
                          ))
                      .toList()))
        ],
      ),
    );
  }

  _tabBar() {
    return TabBar(
        controller: _tabController,
        isScrollable: true,
        labelColor: Colors.black,
        indicator: UnderlineIndicator(
            strokeCap: StrokeCap.round,
            borderSide: BorderSide(color: primary, width: 3),
            insets: EdgeInsets.only(left: 15, right: 15)),
        tabs: categoryList.map<Tab>((tab) {
          return Tab(
              child: Padding(
            padding: EdgeInsets.only(left: 5, right: 5),
            child: Text(
              tab.name ?? "",
              style: TextStyle(fontSize: 16),
            ),
          ));
        }).toList());
  }

  @override
  bool get wantKeepAlive => true;

  void loadData() async {
    try {
      HomeModel result = await HomeDao.get("推荐");
      print(result);
      if (result.categoryList != null) {
        _tabController = TabController(
            length: result.categoryList?.length ?? 0, vsync: this);
      }
      setState(() {
        categoryList = result.categoryList ?? [];
        bannerList = result.bannerList ?? [];
      });
    } on NeedAuth catch (e) {
      showWarnToast(e.message);
      setState(() {
        // _isLoading = false;
      });
    } on SunNetError catch (e) {
      showWarnToast(e.message);
      setState(() {
        // _isLoading = false;
      });
    }
  }

  _appBar() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 15),
      child: Row(
        children: [
          InkWell(
              onTap: () {
                if (widget.onJumpTo != null) {
                  widget.onJumpTo!(3);
                }
              },
              child: ClipRRect(
                borderRadius: BorderRadius.circular(23),
                child: Image(
                  height: 46,
                  width: 46,
                  image: AssetImage('images/avatar.png'),
                ),
              )),
          Expanded(
              child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 15),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(16),
              child: Container(
                padding: EdgeInsets.only(left: 10, top: 3),
                height: 32,
                alignment: Alignment.centerLeft,
                child: Icon(
                  Icons.search,
                  color: Colors.grey,
                  size: 20,
                ),
                decoration: BoxDecoration(color: Colors.grey[100]),
              ),
            ),
          )),
          InkWell(
            onTap: () {},
            child: Icon(
              Icons.explore_outlined,
              color: Colors.grey,
            ),
          ),
          InkWell(
            onTap: () {},
            child: Padding(
              padding: EdgeInsets.only(left: 12),
              child: Icon(Icons.mail_outline, color: Colors.grey),
            ),
          )
        ],
      ),
    );
  }
}
